<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:44
 */

namespace app\admin\service\business\controllers\Access\Role;


use app\admin\service\business\BaseControllerService;
use app\admin\service\business\controllers\Access\Role\Models\AdminRoleModel;
use app\admin\service\business\controllers\Access\Role\Models\MixedModel;
use think\facade\Db;

/**
 * Class AdminRoleService
 *
 * @property-read AdminRoleModel $model
 * @property-read MixedModel $mixed
 *
 * @package app\admin\service\business\controllers\Access\Role
 */
class AdminRoleService extends BaseControllerService
{
    protected $rely = [
        'model' => AdminRoleModel::class,
        'mixed' => MixedModel::class,
    ];

    /**
     * 查询列表
     *
     * @param array $where
     * @param int $limit
     * @return mixed
     */
    public function resList(array $where, int $limit)
    {
        $list = $this->model->getList($where['key'] ?? [], [], true, $limit);

        foreach($list as $k => $v) {
            $list[$k] -> routes = json_encode(explode("\n", $v -> routes));
        }

        return $list;
    }

    /**
     * 查询单条信息
     *
     * @param int $id
     * @return mixed
     */
    public function resFind(int $id)
    {
        $result = $this->model->getFind($id);

        // 拥有的权限
        $result -> ruleIds = implode(',', $result -> rules -> column('id'));

        return $result;
    }

    /**
     * 操作数据
     *
     * @param array $params
     * @param int $id
     * @return array
     */
    public function operating(array $params, int $id = 0): array
    {
        // 判断 name 是否重复
        if ($this->model->isUnique($params['name'], $id)) return echoArr(500, '当前名称重复');

        // 处理权限
        if(!$ruleIds = $this -> mixed -> getRuleIds(explode(',', $params['rules']))) return echoArr(500, '请选择权限');

        // 需操作的数据
        $data = [
            'name' => $params['name'],
            'description' => $params['description']
        ];


        // 开启事务
        Db::startTrans();

        try {
            // 执行数据更新
            if ($id) {
                $result = $this->model->edit($data, $id);
            } else {
                $result = $this->model->insert($data);
            }

            // 新增自增id
            if(!$id) $id = $result -> id;

            // 更新角色权限
            $this -> model -> updateRule($id, $ruleIds);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return echoArr(800);
        }

        return echoArr(200);
    }


    /**
     * 删除数据
     *
     * @param int $id
     * @return array
     */
    public function del(int $id): array
    {
        // 判断是否绑定管理员
        if($this -> model -> isAdminRole($id)) return echoArr(500, '当前角色被管理员绑定，请先移除');

        // 判断是否绑定菜单
        if($this -> model -> isMenuRole($id)) return echoArr(500, '当前角色被菜单绑定，请先移除');

        // 开启事务
        Db::startTrans();

        try {
            // 更新权限
            $this -> model -> updateRule($id, []);

            // 删除角色
            $this -> model -> delete($id);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();

            return echoArr(800);
        }

        return echoArr(200, '操作成功');
    }

    /**
     * 获取权限列表
     *
     * @return mixed
     */
    public function getRuleList(){
        $list = $this -> mixed -> getRuleList() -> toArray();

        array_walk($list, function (&$value){
            $value['name'] = $value['method'] . '——' . $value['name'];
        });

        return $list;
    }
}
